﻿using System;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.WindowsAzure.StorageClient;
using System.Collections.Generic;
using AntsCode.StorageClientExtensions.Helpers;
using System.Data.Services.Client;

namespace AntsCode.StorageClientExtensions.QueryHandlers
{
    /// <summary>
    /// Handles a Take query
    /// </summary>
    /// <typeparam name="T">The source type.</typeparam>
    internal class TakeQueryHandler<T> : QueryHandler
    {
        public TakeQueryHandler(QueryExecutor queryExecutor, MethodCallExpression m, IQueryable<T> data, ContinuationToken continuationToken)
            : base(data, continuationToken)
        {
            if (data != null)
            {
                ConstantExpression ce = (ConstantExpression)m.Arguments[1];
                int count = (int)ce.Value;

                // Apply Take method
                data = data.Take(count);

                if (data.GetType() == typeof(DataServiceQuery<T>))
                {
                    queryExecutor.IncrementQueryBatchNo();
                    this.Data = queryExecutor.ExecuteAll((DataServiceQuery<T>)data, ref continuationToken);
                }
                else
                {
                    this.Data = data;
                }

                this.ContinuationToken = continuationToken;
            }
        }
    }
}
